package com.kuaimacode.kframework.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuaimacode.kframework.api.service.sys.SysOpLogService;
import com.kuaimacode.kframework.api.vo.request.LocationReq;
import com.kuaimacode.kframework.api.vo.request.MasterReq;
import com.kuaimacode.kframework.api.vo.response.ComplainMasterResp;
import com.kuaimacode.kframework.api.vo.response.LocationResp;
import com.kuaimacode.kframework.api.vo.response.MasterResp;
import com.kuaimacode.kframework.api.vo.response.ServiceTypeResp;
import com.kuaimacode.kframework.constants.MasterConstants;
import com.kuaimacode.kframework.mybatis.mapper.master.UserMasterMapper;
import com.kuaimacode.kframework.mybatis.models.category.AgentServ;
import com.kuaimacode.kframework.mybatis.models.master.MasterData;
import com.kuaimacode.kframework.mybatis.models.master.MasterMessage;
import com.kuaimacode.kframework.mybatis.models.master.UserLocation;
import com.kuaimacode.kframework.mybatis.models.master.UserMaster;
import com.kuaimacode.kframework.mybatis.models.sys.SysOpLog;
import com.kuaimacode.kframework.mybatis.models.user.Order;
import com.kuaimacode.kframework.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserMasterService extends ServiceImpl<UserMasterMapper,UserMaster> {
    @Autowired
    private MasterScoreDetailsService detailsService;

    @Autowired
    private ScoreManagentmentService scoreManagentmentService;

    @Autowired
    private SysOpLogService opLogService;

    private static final String CONSTANTS_1 = "0";

    private static final String TIME_LASTER_23 = " 23:59:59";

    private static final String TIME_CURRENT_00 = " 00:00:00";



    public UserMaster getUserMasterByUserId(Long userId) {
        QueryWrapper<UserMaster> qr = new QueryWrapper<>();
        qr.eq("user_id",userId);
        qr.in("status","1","2");
        return baseMapper.selectOne(qr);
    }

    @Transactional
    public boolean saveOrUpdate(UserMaster master,boolean addFlag){
        if (addFlag){
            return baseMapper.insert(master)>0;
        }else{
            return baseMapper.updateById(master)>0;
        }
    }

    public ComplainMasterResp findMasterData(Long userId){
        ComplainMasterResp complainMasterResp = new ComplainMasterResp();
        MasterData data = baseMapper.findMasterData(userId);
        if (data != null){
            BeanUtils.copyProperties(data,complainMasterResp);
        }
        return complainMasterResp;
    }

    /**
     * 获取userMaster对应的技能
     * @param userId
     * @return
     */
    public Map<String,String> getMasterServiceType(Long userId){
        Map<String,String> map = new HashMap<>();
        QueryWrapper<UserMaster> qr = new QueryWrapper<>();
        qr.eq("user_id",userId);
        qr.eq("status", "1");
        UserMaster master = baseMapper.selectOne(qr);

        if (master!=null){
            JSONObject object = JSON.parseObject(master.getSkillType());
            for (Map.Entry<String, Object> entry : object.entrySet()) {
                map.put(entry.getKey(),String.valueOf(entry.getValue()));
            }
        }
        return map;
    }


    public List<ServiceTypeResp> getSkillTypeByAgentId(List<AgentServ> serv) {
        List<ServiceTypeResp> typeResps = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(serv)){
            for (AgentServ serv1:serv) {
                ServiceTypeResp typeResp = new ServiceTypeResp();
                BeanUtils.copyProperties(serv1,typeResp);
                typeResps.add(typeResp);
            }
        }
        return typeResps;
    }

    public List<LocationResp> getNearRider(LocationReq req,String agentId){
        List<LocationResp> resps = new ArrayList<>();
        if (req.getDistance()==null||req.getDistance()==0){
            req.setDistance(MasterConstants.KILO_METRE);
        }else{
            req.setDistance(req.getDistance());
        }
        //获取分站骑手的位置
        List<UserLocation> locations = baseMapper.findNearMasterLocaion(Double.parseDouble(req.getLongitude()),
                Double.parseDouble(req.getLatitude()),
                req.getDistance(),
                agentId,
                MasterConstants.YSS,
                MasterConstants.YSS);
        if (CollectionUtils.isNotEmpty(locations)){
            for (UserLocation location:locations) {
                LocationResp resp = new LocationResp();
                if (StringUtils.isNotEmpty(location.getSkillType())){
                    JSONObject object = JSONObject.parseObject(location.getSkillType());
                    if (object !=null){
                        if (StringUtils.isNotEmpty(req.getType())&&object.getString(req.getType())!=null){
                            if ("1".equals(req.getType())){
                                BeanUtils.copyProperties(location,resp);
                                resp.setLatitude(String.valueOf(location.getLatitude()));
                                resp.setLongitude(String.valueOf(location.getLongitude()));
                                resps.add(resp);
                            }else{
                                if (object.getString(req.getType()).contains(String.valueOf(req.getChildType()))){
                                    BeanUtils.copyProperties(location,resp);
                                    resp.setLatitude(String.valueOf(location.getLatitude()));
                                    resp.setLongitude(String.valueOf(location.getLongitude()));
                                    resps.add(resp);
                                }
                            }
                        }
                    }
                }
            }
        }
        return resps;
    }


    /**
     * 获取附近师傅
     * @param masterReq
     * @param serviceClass1 服务大类
     * @return
     */
    public List<MasterResp> getNearMasterBySkillType(MasterReq masterReq,String serviceClass1){
        //获取分站骑手的位置
        List<MasterResp> masterResps = new ArrayList<>();
        List<UserLocation> locations = baseMapper.findNearMasterLocaion(Double.parseDouble(masterReq.getLongitude()),
                Double.parseDouble(masterReq.getLatitude()),
                Integer.parseInt(masterReq.getDistance()),
                masterReq.getAgentId(),
                MasterConstants.YSS,
                MasterConstants.YSS);
        if (CollectionUtils.isNotEmpty(locations)){
            locations.forEach(item->{
                MasterResp masterResp = new MasterResp();
                boolean flag = false;
                Map<String,String> map = getMasterServiceType(item.getUserId());
                if (MapUtils.isNotEmpty(map)){
                    map.forEach((k,v)->{
                        String skill = map.get(k);
                        if (StringUtils.isNotEmpty(skill)){
                            List<String> skillStr = new ArrayList<>();
                            if (skill.contains(",")){
                                String[] args = skill.split(",");
                                for (int i = 0; i < args.length; i++) {
                                    String skillParam = args[i];
                                    if (org.apache.commons.lang3.StringUtils.equals(skillParam,masterReq.getServiceClass())){
                                        masterResp.setStarLevel(item.getStarLevel());
                                        masterResp.setMasterName(item.getName());
                                        masterResp.setMasterId(String.valueOf(item.getUserId()));
                                    }
                                }
                            }else{
                                if (org.apache.commons.lang3.StringUtils.equals(skill,masterReq.getServiceClass())){
                                    masterResp.setStarLevel(item.getStarLevel());
                                    masterResp.setMasterName(item.getName());
                                    masterResp.setMasterId(String.valueOf(item.getUserId()));
                                }
                            }
                        }
                    });
                }
                if (StringUtils.isNotEmpty(masterResp.getMasterId())){
                    masterResps.add(masterResp);
                }
            });
        }
        return masterResps;
    }

    //拒绝订单扣分
    public boolean refusedScore(Order order){
        Long score = scoreManagentmentService.computingScore(Long.parseLong(order.getAgentId()),null,false,false,false,false,false,true,false);
        if (score!=null&&score!=0){
            detailsService.insertScore(order.getMasterId(),"拒绝订单",order.getOrderNo(),String.valueOf(score),"惩罚");
        }
        UserMaster master1 = this.getUserMasterByUserId(order.getMasterId());
        if (master1!=null){
            Integer scores =  Integer.parseInt(org.apache.commons.lang3.StringUtils.isNotEmpty(master1.getScore())?master1.getScore():"0")-Integer.parseInt(String.valueOf(score));
            if(scores <0){
                scores = 0;
            }
            master1.setScore(String.valueOf(scores));
            //计算星级
            String star = scoreManagentmentService.parseStar(Long.parseLong(String.valueOf(scores)));
            master1.setMasterStars(star);
            this.saveOrUpdate(master1,false);
        }
        return true;
    }

    public List<MasterMessage> findAllMasterMessage(Long id){
        List<MasterMessage> datas = baseMapper.findMasterMessage(id,null,null,null,null,null);
        return datas;
    }

    public int updateMasterOpLog(){
        List<UserMaster> masters = baseMapper.findOnlineMaster("1","1");
        int num = 0;
        for (UserMaster master : masters) {
            for (int i = 0; i <2 ; i++) {
                insertSysOpLog(String.valueOf(i),master.getUserId());
                num++;
            }
        }
        return num;
    }

    private void insertSysOpLog(String type,Long userId){
        Date now = new Date();
        Date after = DateUtil.dateMinusDay();
        String nowStr = DateUtil.dateToString(now,DateUtil.LONG_DATE_FORMAT);
        Date nowDate = DateUtil.stringtoDate(nowStr+TIME_CURRENT_00,DateUtil.FORMAT_ONE);
        String afterStr = DateUtil.dateToString(after,DateUtil.LONG_DATE_FORMAT);
        Date afterDate = DateUtil.stringtoDate(afterStr+TIME_LASTER_23,DateUtil.FORMAT_ONE);
        SysOpLog opLog = new SysOpLog();
        opLog.setUserId(userId);
        opLog.setType("0");
        if (org.apache.commons.lang3.StringUtils.equals(CONSTANTS_1,type)){
            //下线
            opLog.setCreatedTime(afterDate);
            opLog.setUpdateTime(afterDate);
            opLog.setRemark("下线");
        }else{
            //上线
            opLog.setCreatedTime(nowDate);
            opLog.setUpdateTime(nowDate);
            opLog.setRemark("上线");
        }
        opLogService.saveOrUpdate(opLog,true);

    }
}
